package com.leo.blog.login.handler;




import com.leo.blog.login.SelfUserEntity;
import com.leo.blog.login.config.JWTConfig;
import com.leo.blog.login.config.JWTTokenUtil;
import com.leo.blog.util.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/6/11 15:10
 * @since JDK 1.8
 */
@Slf4j
@Component
public class UserLoginSuccessHandler implements AuthenticationSuccessHandler {

    /**
     * 登录成功返回结果
     * @Author Sans
     * @CreateTime 2019/10/3 9:27
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication){
        // 组装JWT
        SelfUserEntity selfUserEntity =  (SelfUserEntity) authentication.getPrincipal();
        String token = JWTTokenUtil.createAccessToken(selfUserEntity);
        token = JWTConfig.tokenPrefix + token;
        // 封装返回参数
        Map<String,Object> resultData = new HashMap<>();
        resultData.put("code","200");
        resultData.put("msg", "登录成功");
        resultData.put("token",token);
        resultData.put("redirect","/admin/adminindex.html");
        System.out.println("登入成功");
        Cookie cookie = new Cookie("AuthToken",token);
        cookie.setHttpOnly(false);
        cookie.setSecure(false);
        cookie.setMaxAge(-1);
        cookie.setPath("/");
        response.addCookie(cookie);
        ResultUtil.responseJson(response,resultData);

    }
}
